<template>
  <el-drawer
    title="添加 / 编辑"
    size="45%"
    :wrapperClosable="false"
    :visible.sync="showModify"
  >
    <template slot="title">
      <span class="title">添加 / 编辑</span>
      <div class="btn-wrap">
        <el-button size="small" @click="close">关闭</el-button>
        <el-button type="primary" size="small" @click="save">提交</el-button>
      </div>
    </template>
    <div class="modifyGlobalRule common-container">
      <el-form ref="form" :model="form">
        <el-card class="box-card" style="margin-top: 10px">
          <div slot="header" class="clearfix">
            <span>全局配置名称</span>
          </div>
          <el-input v-model="form.name"></el-input>
        </el-card>
        <el-card
          style="margin-top: 10px"
          class="box-card"
          v-for="(item, index) in fieldsList"
          :key="index"
        >
          <div slot="header" class="clearfix">
            <span>{{ item.fieldName }}</span>
          </div>
          <el-form-item
            v-for="(fItem, fIndex) in item.fieldsList"
            :key="fIndex"
            required
            :label="fItem.detail"
          >
            <el-input v-if="fItem.onOff" v-model="fItem.def.value">
              <template slot="prepend">
                是否开启：
                <el-switch v-model="fItem.def.enable"></el-switch>
              </template>
            </el-input>
            <template v-else>
              <el-switch
                v-if="fItem.type === 'boolean'"
                v-model="fItem.def"
              ></el-switch>
              <el-input
                v-else-if="fItem.type === 'int'"
                v-model="fItem.def"
                type="number"
              ></el-input>
              <el-input
                v-else-if="fItem.type === 'object'"
                v-model="fItem.def"
                type="textarea"
                :rows="5"
              ></el-input>
              <el-input v-else v-model="fItem.def"></el-input>
            </template>
          </el-form-item>
        </el-card>
      </el-form>
    </div>
  </el-drawer>
</template>
<script>
import Api from "@/api/";
import prettyJson from 'json-stringify-pretty-compact';

export default {
  props: {
    showModify: {
      type: Boolean,
      default: false,
    },
    type: {
      type: String,
      default: "add",
    },
    id: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      disciplineOptions: [],
      fieldsList: [],
      form: {
        formId: 0,
        name: "",
        enable: false,
      },
    };
  },
  watch: {
    async showModify(val) {
      if (val) {
        if (this.type == "edit") {
          this.getInfo();
        }
      }
    },
  },
  methods: {
    close() {
      this.$emit("close");
      this.resetForm();
    },
    resetForm() {
      this.form = {
        formId: 0,
        name: "",
        enable: false,
      };
    },
    //
    getInfo() {
      Api.globalRule
        .detail({
          targetId: this.id,
        })
        .then((res) => {
          this.form = {
            formId: res.data.id,
            name: res.data.name,
            enable: res.data.enable,
          };
          for (let i = 0; i < this.fieldsList.length; i++) {
            for (let j = 0; j < this.fieldsList[i].fieldsList.length; j++) {
              for (let k in res.data.setting) {
                if (k == this.fieldsList[i].fieldsList[j].key) {
                  if (this.fieldsList[i].fieldsList[j].type === 'object') {
                    this.fieldsList[i].fieldsList[j].def = prettyJson(res.data.setting[k]);
                  } else {
                    this.fieldsList[i].fieldsList[j].def = res.data.setting[k];
                  }
                }
              }
            }
          }
        });
    },
    checkInfo() {
      if (String(this.form.name).trim() == "") {
        this.$message({
          type: "error",
          message: "请填写名称",
        });
        return false;
      }
      return true;
    },
    save() {
      if (!this.checkInfo()) {
        return;
      }
      let form = JSON.parse(JSON.stringify(this.form));
      form.setting = {};
      for (let i = 0; i < this.fieldsList.length; i++) {
        for (let j = 0; j < this.fieldsList[i].fieldsList.length; j++) {
          if (this.fieldsList[i].fieldsList[j].type === 'object') {
            form.setting[this.fieldsList[i].fieldsList[j].key] =
              JSON.parse(this.fieldsList[i].fieldsList[j].def);
          }else {
            form.setting[this.fieldsList[i].fieldsList[j].key] =
              this.fieldsList[i].fieldsList[j].def;
          }
        }
      }
      Api.globalRule
        .edit(form)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success("操作成功");
            this.$emit("close");
          }
        })
        .catch((err) => {
        });
    },
    getFileds() {
      return new Promise((resolve, reject) => {
        Api.globalRule
          .fieldsList({})
          .then((res) => {
            let settingObj = {};
            res.data.forEach((item) => {
              settingObj[item.group] = {
                fieldName: item.group,
                fieldsList: [],
              };
            });
            for (let k in settingObj) {
              res.data.forEach((item) => {
                if (item.group == k) {
                  if (item.onOff) {
                    item.def = {
                      enable: true,
                      value: "",
                    };
                  }
                  settingObj[k].fieldsList.push(item);
                }
              });
            }
            let fieldsList = [];
            for (let k in settingObj) {
              fieldsList.push(settingObj[k]);
            }
            console.log(fieldsList);
            this.fieldsList = fieldsList;
            resolve();
          })
          .catch((err) => {
            reject();
          });
      });
    },
  },
  async mounted() {
    await this.getFileds();
    if (this.$route.query.type == "edit") {
      this.getInfo();
    }
  },
};
</script>
<style scoped lang="scss">
.modifyGlobalRule {
  .modify-bot {
    width: 70%;
    padding: 30px 10px;
  }
}
</style>
